using System;
using System.Text.Json;
using LightCAD.MathLib;

namespace LightCAD.Core.Elements
{
    public class Point : LcElement
    {
        public Vector2 P;
        public Point()
        {
        }
        public Point(Vector2 p)
        {
            this.P = p;
        }
        public Point(double x, double y)
        {
            this.P.X = x;
            this.P.Y = y;
        }

        public override LcElement Clone()
        {
            var clone = new Point();
            clone.Copy(this);
            return clone;
        }

        public override void Copy(LcElement src)
        {
            base.Copy(src);
            this.P = ((Point)src).P;
        }
        private double GetAngel(Vector2 p, Vector2 basep)
        {
            int X = Convert.ToInt32(p.X);
            int Y = Convert.ToInt32(p.Y);

            Vector2 a1 = new Vector2(X, Y);
            Vector2 a2 = new Vector2(X, 300);
            Vector2 b1 = new Vector2(X, Y);
            Vector2 b2 = new Vector2(basep.X, basep.Y);
            var a = Math.Atan2(a2.Y - a1.Y, a2.X - a1.X);
            var b = Math.Atan2(b2.Y - b1.Y, b2.X - b1.X);
            double angle = 180 * (b - a) / Math.PI;
            return (angle > 0 ? angle : angle + 360);
        }
        public override void Scale(Vector2 factor, double length)
        {
            Matrix3 matrix3 = Matrix3.GetScale(length, factor);
            this.P = matrix3.MultiplyPoint(this.P);
        }

        public void Set(Vector2 p, bool fireChangedEvent = false)
        {
            //PropertySetter:P
            if (!fireChangedEvent)
            {
                if (p != null) this.P = p;
            }
            else
            {
                bool chg_p = (p != null && p != this.P);
                if (chg_p)
                {
                    OnPropertyChangedBefore(nameof(P), this.P, p);
                    var oldValue = this.P;
                    this.P = p;
                    OnPropertyChangedAfter(nameof(P), oldValue, this.P);
                }
            }
        }


        public override void WriteProperties(Utf8JsonWriter writer, JsonSerializerOptions soptions)
        {
            writer.WriteVector2dProperty(nameof(this.P), this.P);
        }
        public override void ReadProperties(ref JsonElement jele)
        {
            this.P = jele.ReadVector2dProperty(nameof(P));
        }
    }
}